package com.goldze.mvvmhabit.ui.tab_bar.fragment.leave;

import android.Manifest;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.TimePicker;

import com.goldze.mvvmhabit.BR;
import com.goldze.mvvmhabit.R;
import com.goldze.mvvmhabit.app.AppViewModelFactory;
import com.goldze.mvvmhabit.databinding.FragmentLeaveBinding;
import com.goldze.mvvmhabit.utils.GlideImageLoader;
import com.goldze.mvvmhabit.utils.UserManager;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.FileUtil;

/**
 * Created by goldze on 2018/7/18.
 */

public class LeaveFragment extends BaseFragment<FragmentLeaveBinding, LeaveViewModel> implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {

    private Calendar calendar;
    private DateFormat dateFormat;
    private SimpleDateFormat timeFormat;
    private String TIME_PATTERN = "HH:mm";
    private boolean isEndTime = false;
    private int year;
    private int month;
    private int dayOfMonth;
    private String cacheTime = "";
    private final int SELECTPIC_RESULT_CODE = 1;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_leave;
    }

    @Override
    public LeaveViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(LeaveViewModel.class);
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.bannerUrl.observe(this, new Observer<List<String>>() {
            @Override
            public void onChanged(@Nullable List<String> list) {
                binding.mainBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
                binding.mainBanner.setImageLoader(new GlideImageLoader());
                binding.mainBanner.setImages(list);
                binding.mainBanner.setBannerTitles(list);
                binding.mainBanner.setBannerAnimation(Transformer.DepthPage);
                binding.mainBanner.isAutoPlay(true);
                binding.mainBanner.setDelayTime(3000);
                binding.mainBanner.setIndicatorGravity(BannerConfig.CIRCLE_INDICATOR);
                binding.mainBanner.start();
            }
        });

        viewModel.typeList.observe(this, new Observer<List<String>>() {
            @Override
            public void onChanged(@Nullable List<String> list) {
                binding.niceSpinner.attachDataSource(list);
                binding.niceSpinner.setTextColor(getActivity().getColor(R.color.color_303030));
                binding.niceSpinner.setTextSize(16);
                binding.niceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        viewModel.selectTypeId(position);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                });
            }
        });

        viewModel.startTimeEvent.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String value) {
                cacheTime = "";
                isEndTime = false;
                new DatePickerDialog(getActivity(), LeaveFragment.this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });

        viewModel.endTimeEvent.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String value) {
                cacheTime = "";
                isEndTime = true;
                new DatePickerDialog(getActivity(), LeaveFragment.this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });

        viewModel.selectAlbum.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                requestCameraPermissions();
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.addDefaultImgaeList(null);
        viewModel.getGetBannerList();
        viewModel.getTypeList();

        calendar = Calendar.getInstance();
        dateFormat = DateFormat.getDateInstance(DateFormat.LONG, Locale.getDefault());
        timeFormat = new SimpleDateFormat(TIME_PATTERN, Locale.getDefault());

        if (UserManager.getAppManager().isLogin()) {
            viewModel.name.setValue(UserManager.getAppManager().getmUserInfo().getNickName());
            viewModel.departName.setValue(UserManager.getAppManager().getmUserInfo().getDepartmentName());
        } else {
            viewModel.name.setValue("");
            viewModel.departName.setValue("");
        }
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        this.year = year;
        this.month = month + 1;
        this.dayOfMonth = dayOfMonth;
        cacheTime = year + "-" + this.month + "-" + dayOfMonth + "T";
        new TimePickerDialog(getActivity(), LeaveFragment.this, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true).show();
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        String hourStr = "";
        String minuteStr = "";
        if (String.valueOf(hourOfDay).length() == 1) {
            hourStr = "0" + hourOfDay;
        } else {
            hourStr = String.valueOf(hourOfDay);
        }

        if (String.valueOf(minute).length() == 1) {
            minuteStr = "0" + minute;
        } else {
            minuteStr = String.valueOf(minute);
        }
        cacheTime = cacheTime + hourStr + ":" + minuteStr + ":00." + "000Z";
        if (isEndTime) {
            viewModel.setEndTime(cacheTime);
            viewModel.endTimeValue.set(year + "年" + month + "月" + dayOfMonth +
                    "日 " + hourStr + ":" + minuteStr);
        } else {
            viewModel.setStartTime(cacheTime);
            viewModel.startTimeValue.set(year + "年" + month + "月" + dayOfMonth +
                    "日 " + hourStr + ":" + minuteStr);

        }
    }

    /**
     * 请求相机权限
     */
    public void requestCameraPermissions() {
        //请求打开相机权限
        RxPermissions rxPermissions = new RxPermissions(getActivity());
        rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Intent albumIntent = new Intent(Intent.ACTION_PICK);
                            albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(albumIntent, SELECTPIC_RESULT_CODE);
                        }
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SELECTPIC_RESULT_CODE:
                Uri mUri = data.getData();
                String path = FileUtil.getFilePathByUri(getActivity(), mUri);
                viewModel.addDefaultImgaeList(path);
                break;

            default:
                break;
        }
    }


}
